package com.chushouya.product.dao.repository;

import com.general.framework.core.enums.DelFlagEnum;
import com.general.framework.core.lang.Lists;
import com.general.framework.core.lang.Longs;
import com.general.framework.core.lang.Strings;
import com.general.framework.core.schema.PageResult;
import com.general.framework.data.mybatis.BaseRepository;
import com.chushouya.product.dao.entity.ProductEntity;
import com.chushouya.product.dao.mapper.ProductEntityMapper;
import com.chushouya.product.dto.admin.product.query.ProductQuery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Objects;


@Slf4j
@Repository
public class ProductRepository extends BaseRepository<ProductEntityMapper, ProductEntity, Long> {

    public List<ProductEntity> selectList(ProductQuery query) {
        return this.selectByExample(this.buildExample(query));
    }

    public PageResult<ProductEntity> selectPage(ProductQuery query) {
        return this.selectPage(query.getPageRequest(), this.buildExample(query));
    }

    public ProductEntity selectOne(ProductQuery query) {
        return this.selectFirstOneByExample(this.buildExample(query));
    }

    private Example buildExample(ProductQuery query) {
        Example example = this.buildExample();
        if (Longs.notNullAndZero(query.getCategoryId())) {
            example.and().andEqualTo("categoryId", query.getCategoryId());
        }
        if (Longs.notNullAndZero(query.getBrandId())) {
            example.and().andEqualTo("brandId", query.getBrandId());
        }
        if (Strings.isNotEmpty(query.getProductName())) {
            example.and().andLike("productName", Strings.format("%{}%", query.getProductName().replaceAll(" ", "").toLowerCase()))
                    .orLike("keywords", Strings.format("%{}%", query.getProductName().replaceAll(" ", "").toLowerCase()));
        }
        if (Strings.isNotEmpty(query.getKeywords())) {
            example.and().andLike("productName", Strings.format("%{}%", query.getKeywords().replaceAll(" ", "").toLowerCase()))
                    .orLike("keywords",  Strings.format("%{}%", query.getKeywords().replaceAll(" ", "").toLowerCase()));
        }
        if (Lists.isNotEmpty(query.getCategoryIdList())) {
            example.and().andIn("categoryId", query.getCategoryIdList());
        }
        if (Longs.notNullAndZero(query.getSeriesId())) {
            example.and().andEqualTo("seriesId", query.getSeriesId());
        }
        if (Objects.nonNull(query.getStatus())) {
            example.and().andEqualTo("status", query.getStatus());
        }
        if (Lists.isNotEmpty(query.getProductIdList())) {
            example.and().andIn("productId", query.getProductIdList());
        }
        example.and().andEqualTo("delFlag", DelFlagEnum.normal.getValue());
        example.orderBy("sort").asc().orderBy("productId").desc();
        return example;
    }

}